// 报表预定义
import React, { useCallback, useEffect, useState } from 'react';
import { CarryOutOutlined } from '@ant-design/icons';
import { getCategoryTree } from 'src/services/AnalyseManage';
import { TreeSelect } from 'antd';
import { AnalyseCategorySelectProp } from 'src/services/AnalyseManage/type';

const AnalyseCategorySelect = ( props: AnalyseCategorySelectProp ) => {
	const { onSelect, type } = props;
	const [ treeData, setTreeData ] = useState( [] );

	const buildChild = useCallback( ( item: any ) => {
		if( !item.children ) return;
		let childs = [];
        
		item.children.forEach( ( childrenItem: any ) => {
			let child = buildChild( childrenItem );
			childs.push( {
				...childrenItem,
				title: childrenItem.name,
				key: childrenItem.id,
				children: child,
			} );
		} );
		return childs;
	}, [] );

	const loadDatas = useCallback( async () => {
		let response = await getCategoryTree( { type: type || 'CUSTOMER' } );
		if ( response.data && response.data.success ) {
			let dates = response.data.data;
			let treeData = [];
			dates.forEach( ( item: any ) => {
				let child = buildChild( item );
				treeData.push( {
					...item,
					title: item.name,
					key: item.id,
					children: child,
					icon: <CarryOutOutlined/>
				} );
			} );
			console.log( treeData );
			setTreeData( treeData );

		}
	}, [ buildChild, type ] );

	useEffect( () => {
		loadDatas();
	}, [ loadDatas ] );


	const onTreeSelect = ( value: any, node: any ) => {
		onSelect( node );
	};

	return (
		<TreeSelect
			showSearch
			style={{ width: '100%' }}
			treeData={treeData}
			dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
			placeholder="Please select"
			allowClear
			treeDefaultExpandAll
			onSelect={onTreeSelect}
		></TreeSelect>
	);

};

export default AnalyseCategorySelect;
